/*
 * -- FightActivity.java --
 * 
 * Copyright 2011, Kyan He <kyan.ql.he@gmail.com>
 * 
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package im.kyan.android.googlefight;

import im.kyan.android.googlefight.HistoryAdapter.HistoryRecord;

import java.net.SocketTimeoutException;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

public class FightActivity extends Activity implements View.OnClickListener {
    
    private EditText mInputView;
    
    private HistoryAdapter mHistoryAdapter;
    
    /**
     * Handler for update UI
     */
    private RateHanlder mHanlder = new RateHanlder();
    
    private IRateClient mEngine = new GoogleRateClient();
    
    private LinearLayout mEditor;
    
    /**
     * Used for toggle soft keyboard
     */
    private InputMethodManager mInputManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        
        setContentView(R.layout.main);
        mHistoryAdapter = new HistoryAdapter(getApplicationContext());
        
        mInputView = (EditText) findViewById(R.id.key1);
        
        // Initialize editor layout
        mEditor = (LinearLayout) findViewById(R.id.editor);
        mEditor.setVisibility(View.GONE);
        
        // Initialize Record List
        ((ListView) findViewById(R.id.result)).setAdapter(mHistoryAdapter);

        // Initialize buttons
        findViewById(R.id.add).setOnClickListener(this);
        findViewById(R.id.ok).setOnClickListener(this);
        findViewById(R.id.cancel).setOnClickListener(this);
        
        mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(R.string.delete);
        return super.onPrepareOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.d("kyan", "" + item.getItemId());
        
        mHistoryAdapter.deleteAll();
        mHistoryAdapter.notifyDataSetChanged();
        return super.onOptionsItemSelected(item);
    }    

    /**
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    public void onClick(View v) {
        
        hideSoftKeyboard(v.getWindowToken());
        
        switch(v.getId()) {
        case R.id.add:
            
            mEditor.setVisibility(View.VISIBLE);
            
            // clear previous input
            mInputView.setText("");
            
            break;
        case R.id.ok:

            mEditor.setVisibility(View.GONE);
            
            final String keyword = mInputView.getText().toString();
            final HistoryRecord record = HistoryAdapter
                    .createRecord(keyword);
            mHistoryAdapter.addRecord(record);
            
            // do time-consuming things in separate thread to improve
            // performance
            Runnable rate = new Runnable() {
                public void run() {
                    
                    long rate;
                    try {
                        rate = mEngine.getRate(keyword);
                        record.setRate(rate);
                    } catch (SocketTimeoutException e) {
                        record.setRate(-1);
                    }
                    
                    record.setTimeStamp(System.currentTimeMillis());
                    mHistoryAdapter.updateRecord(record);
                    mHanlder.obtainMessage(0).sendToTarget();
                }
            };
            new Thread(rate, "rate_thread").start();
            
            break;
        case R.id.cancel:
            
            mEditor.setVisibility(View.GONE);
            
            break;
        }
        
    }

    /**
     * hide soft keyboard
     */
    private void hideSoftKeyboard(IBinder token) {
        
        mInputManager.hideSoftInputFromWindow(token,
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    // TODO:
    class TaskQueue {
        
        synchronized void read() {
            
        }
    }
    
    class RateHanlder extends Handler {
        
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mHistoryAdapter.notifyDataSetChanged();
        }
    }
}